package com.tool.app.utils;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import java.util.HashMap;
import java.util.Map;

public class DomToMap {
  
  public static Map<String, Object> toMap(Element element) {
    Map<String, Object> map = new HashMap<>();
    NodeList childNodes = element.getChildNodes();
    for (int i = 0; i < childNodes.getLength(); i++) {
      Node node = childNodes.item(i);
      if (node.getNodeType() == Node.ELEMENT_NODE) {
        Element childElement = (Element) node;
        if (childElement.hasAttributes()) {
          Map<String, Object> childMap = toMap(childElement);
          if (!childMap.isEmpty()) { // check if child map is empty
            map.putAll(childMap);
          }
        } else {
          String nodeValue = childElement.getTextContent();
          if (!nodeValue.isEmpty() && Integer.parseInt(nodeValue) > 0) { // check if node value is greater than 0
            map.put(childElement.getTagName(), Integer.parseInt(nodeValue));
          }
        }
      }
    }
    return map;
  }
  
  public static Map<String, Object> toMap(Document document) {
    return toMap(document.getDocumentElement());
  }
  
}